// --- Implement Cut/Copy/Paste --------------------------------------------
var clipboardNode = null;
var pasteMode = null;
var step=1;

function showMessage(msgID,classID,msgString){
  window.document.getElementById(msgID).className=classID;
  window.document.getElementById(msgID).innerHTML=msgString;
}

function showNextStep(stepID){
    if (window.document.getElementById(stepID).style.display=="none"){
        window.document.getElementById(stepID).style.display="";
        step++;
   }
}

function showNextTutorial(msgID,msgString){
    window.document.getElementById(msgID).innerHTML=msgString;
}
  
  function copyPaste(action, node) {
    switch( action ) {
    case "cut":
    case "copy":
      clipboardNode = node;
      pasteMode = action;
      break;
    case "paste":
      if( !clipboardNode ) {
        alert("Clipoard is empty.");
        break;
      }
      if( pasteMode == "cut" ) {
        // Cut mode: check for recursion and remove source
        var isRecursive = false;
        var cb = clipboardNode.toDict(true, function(dict){
          // If one of the source nodes is the target, we must not move
          if( dict.key == node.data.key )
            isRecursive = true;
        });
        if( isRecursive ) {
          alert("Cannot move a node to a sub node.");
          return;
        }
        node.addChild(cb);
        clipboardNode.remove();
      } else {
        // Copy mode: prevent duplicate keys:
        var cb = clipboardNode.toDict(true, function(dict){
          dict.title = "Copy of " + dict.title;
          delete dict.key; // Remove key, so a new one will be created
        });
        node.addChild(cb);
      }
      clipboardNode = pasteMode = null;
      break;
    default:
      alert("Unhandled clipboard action '" + action + "'");
    }
  };

// --- Contextmenu helper --------------------------------------------------
function bindContextMenu(span) {
	// Add context menu to this node:
    $(span).contextMenu({menu: "myMenu"}, function(action, el, pos) {
		// The event was bound to the <span> tag, but the node object
		// is stored in the parent <li> tag
		var node = $.ui.dynatree.getNode(el);
	  
		switch( action ) {
			case "createfolder":
				if(step==1){
					if(node.data.title=="MUSICA"){
						node.addChild({ title: "Nueva carpeta", isFolder: true, });
						showMessage("T1S1-complete","felicitacion","BIEN !!!");
						showNextStep("T1S2");
					}
					else
						showMessage("T1S1-complete","reintentelo","Por favor, relea la consigna e intente de nuevo.");
				}
			break;		 
		  
		    case "rename":
				if(step==2 || step==3){
					if(node.data.title=="Nueva carpeta"){
						showNextStep("T1S3");
						showMessage("T1S2-complete","felicitacion","");
						editNode(node);
					}	
					else
						showMessage("T1S2-complete","reintentelo","Por favor, relea la consigna e intente de nuevo.");
				}
		  break;
		  case "delete":
			if(node.data.title=="GARDEL" && step==7){
				showMessage("T1S7-complete","felicitacion","BIEN !!!");
				showNextStep("T-complete");
				node.remove();
			}	
		  break;
		  case "copy":
		  case "paste":
			copyPaste(action, node);
			break;
		  default:
			alert("Todo: appply action '" + action + "' to node " + node);
		  }
	});
  };

  
function editNode(node){
	var prevTitle = node.data.title,
    tree = node.tree;
	// Disable dynatree mouse- and key handling
	tree.$widget.unbind();
	// Replace node with <input>
	$(".dynatree-title", node.span).html("<input id='editNode' style='width: 140px ;text-transform: uppercase' value='" + prevTitle + "' onfocus='this.select()' >");
	// Focus <input> and bind keyboard handler
	$("input#editNode")
		.focus()
		.keydown(function(event){
			switch( event.which ) {
				case 27: // [esc]
					// discard changes on [esc]
					$("input#editNode").val(prevTitle);
					$(this).blur();
				break;
		  
				case 13: // [enter]
					// simulate blur to accept new value
					$(this).blur();
				break;
			}
		}).blur(function(event){
		// Accept new value, when user leaves <input>
		var title = $("input#editNode").val().toUpperCase();
		if(title=="TANGO" && step==3){
			showMessage("T1S2-complete","felicitacion","BIEN !!!");
            showNextStep("T1S4");
		}
		else{
			showMessage("T1S2-complete","reintentelo","Por favor, relea la consigna e intente de nuevo.");
			title="Nueva carpeta";
		}
	  node.setTitle(title);
			
	  // Re-enable mouse and keyboard handlling
      tree.$widget.bind();
      node.focus();
	  
    });
}

// --- Init dynatree during startup ----------------------------------------

$(function(){
	$("#tree").dynatree({
		persist: true,
		onActivate: function(node) {
		},
		
		onExpand: function(flag,node) {
			// Close menu on click
			if( $(".contextMenu:visible").length > 0 ){
			  $(".contextMenu").hide();
			}
			
			if(step==4){
				if(!flag && node.data.title=="MUSICA"){ 
					showMessage("T1S4-complete","felicitacion","BIEN !!!");
					showNextStep("T1S5");
				}
			}
			
			if(flag && step==5 && node.data.title=="MUSICA"){ 
				showMessage("T1S5-complete","felicitacion","BIEN !!!");
				showNextStep("T1S6");
			}
		},
		 
		onClick: function(node, event) {
			// Close menu on click
			if( $(".contextMenu:visible").length > 0 ){
				$(".contextMenu").hide();
			}
		},
      
		onKeydown: function(node, event) {
			// Eat keyboard events, when a menu is open
			if( $(".contextMenu:visible").length > 0 )
				return false;

			switch( event.which ) {
			// Open context menu on [Space] key (simulate right click)
			case 32: // [Space]
				$(node.span).trigger("mousedown", {
				preventDefault: true,
				button: 2
				})
				.trigger("mouseup", {
				preventDefault: true,
				pageX: node.span.offsetLeft,
				pageY: node.span.offsetTop,
				button: 2
				});
			return false;

			// Handle Ctrl-C, -X and -V
			case 67:
			if( event.ctrlKey ) { // Ctrl-C
				copyPaste("copy", node);
				return false;
				}
			break;
        
			case 86:
			if( event.ctrlKey ) { // Ctrl-V
				copyPaste("paste", node);
				return false;
			}
			break;
			case 88:
			if( event.ctrlKey ) { // Ctrl-X
				copyPaste("cut", node);
				return false;
			}
			break;
			}
		},
      /*Bind context menu for every node when it's DOM element is created.
        We do it here, so we can also bind to lazy nodes, which do not
        exist at load-time. (abeautifulsite.net menu control does not
        support event delegation)*/
      onCreate: function(node, span){
        bindContextMenu(span);
      },
      /*Load lazy content (to show that context menu will work for new items too)*/
      onLazyRead: function(node){
        node.appendAjax({
          url: "sample-data2.json"
        });
      },
    /* D'n'd, just to show it's compatible with a context menu.
       See http://code.google.com/p/dynatree/issues/detail?id=174 */
    dnd: {
      onDragStart: function(node) {
        /** This function MUST be defined to enable dragging for the tree.
         *  Return false to cancel dragging of node.
         */
        logMsg("tree.onDragStart(%o)", node);
        return true;
      },
      onDragStop: function(node) {
        // This function is optional.
        logMsg("tree.onDragStop(%o)", node);
      },
      autoExpandMS: 1000,
      preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
      onDragEnter: function(node, sourceNode) {
        /** sourceNode may be null for non-dynatree droppables.
         *  Return false to disallow dropping on node. In this case
         *  onDragOver and onDragLeave are not called.
         *  Return 'over', 'before, or 'after' to force a hitMode.
         *  Return ['before', 'after'] to restrict available hitModes.
         *  Any other return value will calc the hitMode from the cursor position.
         */
        logMsg("tree.onDragEnter(%o, %o)", node, sourceNode);
        return true;
      },

	  onDragOver: function(node, sourceNode, hitMode) {
        /** Return false to disallow dropping this node.
         *
         */
        logMsg("tree.onDragOver(%o, %o, %o)", node, sourceNode, hitMode);
        // Prevent dropping a parent below it's own child
        if(node.isDescendantOf(sourceNode)){
          return false;
        }
        // Prohibit creating childs in non-folders (only sorting allowed)
        if( !node.data.isFolder && hitMode === "over" ){
          return "after";
        }
      },
      onDrop: function(node, sourceNode, hitMode, ui, draggable) {
        sourceNode.move(node, hitMode);
		if(step==6 && sourceNode.data.title=="GARDEL" && node.data.title=="TANGO"){ 
			node.addChild({
			title: "GARDEL",
			isFolder: true,
			});
			sourceNode.remove();
			node.expand(true);
			showMessage("T1S6-complete","felicitacion","BIEN !!!");
            showNextStep("T1S7");}
      },
	  onDragLeave: function(node, sourceNode) {
        /** Always called if onDragEnter was called.
         */
        logMsg("tree.onDragLeave(%o, %o)", node, sourceNode);
      }

    }
    });
  });
  
  
  
